import empyrical

import streamlit as st

from core.backtrader_extends.task import local_tasks

from backtrader_extends.engine import run_task


def build_page():
    tasks = list(local_tasks.values())
    print(tasks)

    def _format_x(task):
        return task.name

    task_selected = st.selectbox(label='请选择策略', options=tasks, format_func=lambda x: _format_x(x))

    if st.button('运行策略'):
        with st.spinner('回测进行中，请稍后...'):
            # if symbols and len(symbols):
            #     for t in task_selected:
            #         t.symbols = symbols
            returns,positions, transactions =run_task(task_selected)

            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric(label="年化收益", value='{}%'.format(round(empyrical.annual_return(returns), 3)*100))
            with col2:
                st.metric(label="最大回撤率", value=round(empyrical.max_drawdown(returns), 3))
            with col3:
                st.metric(label="卡玛比率", value=round(empyrical.calmar_ratio(returns), 3))

            # df = res.stats
            df = (1+returns).cumprod()
            import matplotlib.pyplot as plt
            # plt.title('策略运行结果')
            from matplotlib import rcParams
            rcParams['font.family'] = 'SimHei'
            df.plot()

            st.pyplot(plt.gcf())

            # print('累计收益：', round(empyrical.cum_returns_final(returns), 3))
            # print('年化收益：', )
            # print('最大回撤：', )
            # print('夏普比', round(empyrical.sharpe_ratio(returns), 3))
            # print('卡玛比', round(empyrical.calmar_ratio(returns), 3))

            # st.markdown("<strong><u>{}</u></strong>".format(c), unsafe_allow_html=True)



            st.write(transactions)
